package db

import (
	"gitee.com/yysf-xin/dproxy/pkg/app"
	"gorm.io/gorm"
	"os"
	"strings"
)

type Factory func(name string) interface{}

var registry = make(map[string]Factory)

func RegDbType(name string, f Factory) {
	registry[name] = f
}

func OpenDB(cfg *app.DbConfig) gorm.Dialector {
	db := "mysql"
	if strings.HasSuffix(cfg.DbName, ".db") {
		if !cfg.Upgrade {
			_, err := os.Stat(cfg.DbName)
			if err != nil {
				if !os.IsExist(err) {
					cfg.Upgrade = true
				}
			}
			err = nil
		}
		db = "sqlite"
	}
	f := registry[db]
	if f != nil {
		return f(cfg.DbName).(gorm.Dialector)
	}
	return nil
}
